from wall import Wall
import pygame,random,re

def create_wall(walls,win,s):
	wall1 = Wall(win,s,random.randint(100,400))
	wall2 = Wall(win,s,580 - wall1.height)
	wall1.rect.top = 1
	wall2.rect.bottom = 700
	walls.append((wall1,wall2))

def add_wall(walls,win,s):
	if walls:
		if walls[-1][0].rect.centerx <= 350:
			create_wall(walls,win,s)
	else:
		create_wall(walls,win,s)
def update(walls,square,over = False):
	if not over:
		for wall in walls.copy():
			wall[0].update()
			wall[1].update()
			if wall[0].rect.right < 0:
				walls.remove(wall)
	else:
		for wall1,wall2 in walls:
			pygame.draw.rect(wall1.win,wall1.s.wall_color,wall1.rect)
			pygame.draw.rect(wall2.win,wall2.s.wall_color,wall2.rect)
	square.update()

def write_to_txt(s):
	try:
		with open('score.txt','r') as file:
			text = file.read()
		score_list = re.findall('.',text)
	except:
		score_list = []
	score_list.append(str(s.score))
	score_list.sort(reverse = True)
	with open('score.txt','w') as file:
		for i in score_list:
			file.write(i)
			file.write('\n')

def write_to(s,square):
	s.over = True
	square.play = False
	write_to_txt(s)

def check_crash(walls,square,s):
	for wall in walls:
		if (square.rect.top<wall[0].rect.bottom or\
			square.rect.bottom>wall[1].rect.top) and \
		   square.rect.right > wall[0].rect.left and \
		   square.rect.left < wall[0].rect.right:
		   write_to(s,square)

	if not s.over:
		if square.rect.bottom > 700 or square.rect.top < 0:
			write_to(s,square)

def plus(walls,square,s):
	for wall in walls:
		if wall[0].rect.right<square.rect.left and \
		    wall[0].pass_ == False:
			s.score += 1
			wall[0].pass_ = True
			with open('now.txt','a') as file:
				file.write(str(s.score))
